import axios from 'axios'
import axiosAdapterUniapp from 'axios-adapter-uniapp'

import $storage from '@/utils/storage.js'
import $config from '@/utils/config.js'

// axios 请求配置
const config = {
  baseURL: $config.BASE_URL,
  adapter: axiosAdapterUniapp,
  timeout: 30000  //设置最大请求时间 毫秒
}

// 实例化 axios
const _axios = axios.create(config)

/* 请求拦截器（请求之前的操作） */
_axios.interceptors.request.use(
  config => {
      //添加token,需要结合自己的实际情况添加，
    config.headers['authentication'] = $storage.getTokenStorage() || '';
    // 应用客户端标识
    config.headers['x-header-client'] = $config.CLIENT_ID;
    return config;
  },
  err => Promise.reject(err)
);

/* 请求之后的操作 */
_axios.interceptors.response.use(
  res => {
    return res;
  },
  err => {
    return Promise.reject(err);
  }
);

const toLoginPage = ()=> {
	$storage.removeTokenStorage()
	uni.navigateTo({
		url: "/pages/login/login"
	})
}


const handleResponseCode = (data, successMessage = false)=> {
	const { code, message } = data
	if(Number(code) === 200 && successMessage) {
		uni.$u.toast(message)
	}else if(Number(code) === 500) {
		uni.$u.toast(message)
		throw message
	}else if(Number(code) === 503 || Number(code) === 506 || Number(code) === 504){
		toLoginPage()
		throw message
	}else if(Number(code) === 507) {
		toLoginPage()
		throw message
	}
}

//封装post,get方法,其他的自行往下加，比如put,delete
const http = {
  get(url = '', params = {}, successMessage = false) {
    return new Promise((resolve, reject) => {
      _axios({
        url,
        params,
        headers: {'Content-Type': 'application/json;charset=UTF-8'},
        method: 'GET'
      }).then(res => {
		if(res.status != 200){
			uni.$u.toast('服务器异常')
			return
		}
		handleResponseCode(res.data, successMessage)
        resolve(res.data)
		return res
      }).catch(error => {
        reject(error)
      })
    })
  },
  
  post(url = '', data = {}, successMessage = false) {
    return new Promise((resolve, reject) => {
      _axios({
        url,
        data: data,
        headers: {'Content-Type': 'application/json;charset=UTF-8'},
        method: 'POST'
      }).then(res => {
		if(res.status != 200){
			uni.$u.toast('服务器异常')
			return;
		}
		handleResponseCode(res.data, successMessage)
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  delete(url = '', data = {}, successMessage = false) {
    return new Promise((resolve, reject) => {
      _axios({
        url,
        data: data,
        headers: {'Content-Type': 'application/json;charset=UTF-8'},
        method: 'DELETE'
      }).then(res => {
		if(res.status != 200){
			uni.$u.toast('服务器异常')
			return;
		}
		handleResponseCode(res.data, successMessage)	  
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default http